import React, { useEffect, useState, useRef, useReducer } from "react";
import { useHistory, useLocation } from "react-router-dom";
import {
  Image,
  Loading,
  Tag,
  Dropdown,
  CascadePickerView,
  Button,
  Toast,
  Popup,
} from "antd-mobile/2x";
import {
  DownFill,
  LeftOutline,
  ArrowDownCircleOutline,
  DownOutline,
} from "antd-mobile-icons";
import api from "../../../api/room";
import BeScroll from "../../../components/loading";
import "./index.scss";
import Item from "antd-mobile/2x/es/components/dropdown/item";
const colors = ["#87d068", "#108ee9", "#2db7f5"];
interface Item {
  desc: string;
  houseCode: string;
  houseImg: string;
  price: number;
  tags: Array<string>;
  title: string;
}
let initState = {
  roomType: [],
  oriented: [],
  floor: [],
  characteristic: [],
  roomTypeVal: [],
  orientedVal: [],
  floorVal: [],
  characteristicVal: [],
};
interface V {
  label: string;
  value: string;
}
function reducer(state: any, action: any) {
  switch (action.type) {
    case "roomType": {
      return {
        ...state,
        roomType: [...action.data],
      };
    }
    case "oriented": {
      return {
        ...state,
        oriented: [...action.data],
      };
    }
    case "characteristic": {
      return {
        ...state,
        characteristic: [...action.data],
      };
    }
    case "floor": {
      return {
        ...state,
        floor: [...action.data],
      };
    }
    case "addRoomType": {
      let arr = [...state.roomTypeVal];
      if (typeof action.data === "number") {
        arr.splice(action.data, 1);
      } else {
        arr.push(action.data);
      }
      return {
        ...state,
        roomTypeVal: [...arr],
      };
    }
    case "addOrientedVal": {
      let arr = [...state.orientedVal];
      if (typeof action.data === "number") {
        arr.splice(action.data, 1);
      } else {
        arr.push(action.data);
      }
      return {
        ...state,
        orientedVal: [...arr],
      };
    }
    case "addCharacteristicVal": {
      let arr = [...state.characteristicVal];
      if (typeof action.data === "number") {
        arr.splice(action.data, 1);
      } else {
        arr.push(action.data);
      }
      return {
        ...state,
        characteristicVal: [...arr],
      };
    }

    case "addFloorVal": {
      let arr = [...state.floorVal];
      if (typeof action.data === "number") {
        arr.splice(action.data, 1);
      } else {
        arr.push(action.data);
      }
      return {
        ...state,
        floorVal: [...arr],
      };
    }
    default: {
      return {
        ...state,
      };
    }
  }
}
let num = 1;
export default function Room() {
  const [state1, dispatch] = useReducer(reducer, initState);
  const select = useRef<any>(null);
  const scroll = useRef<any>(null);
  const { push, goBack } = useHistory();
  const { state } = useLocation<any>();
  const [visible, setVisible] = useState(false);
  const cityId = localStorage.getItem("id");
  const [list, setList] = useState<Item[]>([]);
  const [options, setOptions] = useState<any>([]); //区域选项
  const [rentType, setRentType] = useState<any>([]); //租房类型选项
  const [price, setPrice] = useState<any>([]);
  const [start, setStart] = useState<number>(1);
  const [total, setTotal] = useState(1);
  const [areaVal, setArea] = useState<string | null>(null); //区域只
  const [areaValue, setAreaValue] = useState<(string | null)[]>([]); //区域设置数组
  const [typeValue, setTypeValue] = useState<any>([]); //租房类型
  const [priceVal, setPriceVal] = useState<any>([]); //租房类型

  const toCity = () => {
    push("/city");
  };
  //获取数据
  const getList = () => {
    let newStart = (start - 1) * 10 + 1 || 1,
      newEnd = (start - 1) * 10 + 10;
    let newPrice = priceVal[0]?.slice(6);
    let newType = typeValue[0] || state?.rentType;

    api
      .getRoomList({
        cityId,
        area: areaVal,
        start: newStart,
        end: newEnd,
        rentType: newType,
        price: newPrice,
        roomType: state1.roomTypeVal.join(","),
        oriented: state1.orientedVal.join(","),
        characteristic: state1.characteristicVal.join(","),
        floor: state1.floorVal.join(","),
      })
      .then((res: any) => {
        console.log(res);

        if (total !== res.body.count && total !== 1)
          Toast.show({
            content: `共有${res.body.count}套房子`,
          });
        let newList = list.concat([...res.body.list]);
        setList([...newList]);
        setTotal(res.body.count);
      });
  };
  //首次获取
  useEffect(() => {
    getList();
  }, [start]);

  //监听
  useEffect(() => {
    if (list.length === 0 && num === 1) {
      num++;
      getList();
    }
  }, [list, getList]);
  useEffect(() => {
    api.getRoomCondition({ id: cityId }).then((res: any) => {
      console.log(res);

      dispatch({
        type: "roomType",
        data: res.body.roomType,
      });
      dispatch({
        type: "floor",
        data: res.body.floor,
      });
      dispatch({
        type: "characteristic",
        data: res.body.characteristic,
      });
      dispatch({
        type: "oriented",
        data: res.body.oriented,
      });
      setPrice([...res.body.price]);
      setRentType([...res.body.rentType]);
      setOptions([res.body.area, res.body.subway]);
    });
  }, [cityId]);
  const search = () => {
    num = 1;
    Promise.resolve().then(() => {
      setList([]);
      setStart(1);
    });
    select.current.close(); //关闭下拉菜单
    scroll.current.scroll.refresh(); //dom更新刷新滚动条;
    scroll.current.scroll.y = 0;
    scroll.current.scroll.scrollY = 0;
    scroll.current.scroll.openPullUp(); //从新开启滚动条
  };
  return (
    <div className="roomWarp">
      <div className="searchBoxRoom">
        <LeftOutline onClick={() => goBack()} />
        <div className="left">
          <span onClick={() => toCity()}>
            {localStorage.getItem("city") || "选择城市"}
          </span>
          <b>
            <DownFill />
          </b>
          <input type="text" placeholder="请输入搜索内容" />
        </div>
        <i className="iconfont icon-ditu" onClick={() => push("/map")}></i>
      </div>{" "}
      {/* 下拉筛选 */}
      <Dropdown
        className="sortBox"
        ref={select}
        onChange={(key) => {
          if (key === "ooo") {
            setVisible(true);
          }
        }}
        arrow={<DownOutline />}
      >
        <Dropdown.Item key="sorter" title="区域">
          <CascadePickerView
            options={options}
            value={areaValue}
            onChange={(val) => {
              setAreaValue(val);
              let index =
                val.indexOf("null") === -1 ? val.length : val.indexOf("null");
              setArea(() => {
                return val[index - 1] === "area" || undefined
                  ? null
                  : val[index - 1];
              });
            }}
          />
          <div className="roomAreaBtn">
            <Button>取消</Button>
            <Button color="success" onClick={() => search()}>
              确定
            </Button>
          </div>
        </Dropdown.Item>
        <Dropdown.Item
          key="bizop"
          title="方式"
          arrow={<ArrowDownCircleOutline />}
        >
          <CascadePickerView
            options={rentType}
            value={typeValue}
            onChange={(val) => {
              setTypeValue(val);
            }}
          />
          <div className="roomAreaBtn">
            <Button>取消</Button>
            <Button color="success" onClick={() => search()}>
              确定
            </Button>
          </div>
        </Dropdown.Item>
        <Dropdown.Item key="more" title="租金">
          <CascadePickerView
            options={price}
            value={priceVal}
            onChange={(val) => {
              setPriceVal(val);
            }}
          />
          <div className="roomAreaBtn">
            <Button>取消</Button>
            <Button color="success" onClick={() => search()}>
              确定
            </Button>
          </div>
        </Dropdown.Item>
        <Dropdown.Item key="ooo" title="筛选"></Dropdown.Item>
      </Dropdown>
      {/* 抽屉 */}
      <Popup
        className="AllSearchShop"
        visible={visible}
        onMaskClick={() => {
          setVisible(false);
          select.current.close();
        }}
        position="right"
        bodyStyle={{ maxWidth: "70vw", minWidth: "70vw" }}
      >
        <div className="items">
          <h4>户型</h4>
          {state1.roomType.length > 0 &&
            state1.roomType.map((v: V) => {
              return (
                <span
                  key={v.value + "a"}
                  onClick={() => {
                    let index = state1.roomTypeVal.indexOf(v.value);
                    dispatch({
                      type: "addRoomType",
                      data: index === -1 ? v.value : index,
                    });
                  }}
                  className={
                    state1.roomTypeVal.indexOf(v.value) === -1 ? "" : "active"
                  }
                >
                  {v.label}
                </span>
              );
            })}
        </div>

        <div className="items">
          <h4>朝向</h4>

          {state1.oriented.length > 0 &&
            state1.oriented.map((v: V) => {
              return (
                <span
                  key={v.value + "b"}
                  onClick={() => {
                    let index = state1.orientedVal.indexOf(v.value);
                    dispatch({
                      type: "addOrientedVal",
                      data: index === -1 ? v.value : index,
                    });
                  }}
                  className={
                    state1.orientedVal.indexOf(v.value) === -1 ? "" : "active"
                  }
                >
                  {v.label}
                </span>
              );
            })}
        </div>
        <div className="items">
          <h4>楼层</h4>

          {state1.floor.length > 0 &&
            state1.floor.map((v: V) => {
              return (
                <span
                  key={v.value + "c"}
                  onClick={() => {
                    let index = state1.floorVal.indexOf(v.value);
                    dispatch({
                      type: "addFloorVal",
                      data: index === -1 ? v.value : index,
                    });
                  }}
                  className={
                    state1.floorVal.indexOf(v.value) === -1 ? "" : "active"
                  }
                >
                  {v.label}
                </span>
              );
            })}
        </div>
        <div className="items">
          <h4>房屋亮点</h4>

          {state1.characteristic.length > 0 &&
            state1.characteristic.map((v: V) => {
              return (
                <span
                  key={v.value + "d"}
                  onClick={() => {
                    let index = state1.characteristicVal.indexOf(v.value);
                    dispatch({
                      type: "addCharacteristicVal",
                      data: index === -1 ? v.value : index,
                    });
                  }}
                  className={
                    state1.characteristicVal.indexOf(v.value) === -1
                      ? ""
                      : "active"
                  }
                >
                  {v.label}
                </span>
              );
            })}
        </div>
        <div className="allBtn">
          <Button
            color="danger"
            onClick={() => {
              setVisible(false);
              select.current.close();
            }}
          >
            取消
          </Button>
          <Button
            color="success"
            onClick={() => {
              num = 1;
              setVisible(false);
              select.current.close();
              setList([]);
            }}
          >
            确认
          </Button>
        </div>
      </Popup>
      <div className="roomListBox">
        <BeScroll
          ref={scroll}
          myClass="roomWarpScroll"
          setStart={setStart}
          start={start}
          total={total}
        >
          <div className="roomContentBox">
            {list.length > 0 &&
              list.map((v: Item, index: number) => {
                return (
                  <div
                    onClick={() => {
                      push({
                        pathname: "/details",
                        state: {
                          id: v.houseCode,
                        },
                      });
                    }}
                    className="roomList_item"
                    key={index}
                  >
                    <div className="item_img">
                      <Image
                        lazy
                        width={120}
                        height={100}
                        placeholder={<Loading />}
                        src={"http://47.102.145.189:8009" + v.houseImg}
                      />
                    </div>
                    <div className="item_content">
                      <h4>{v.title}</h4>
                      <p style={{ color: "#999", fontSize: "10px" }}>
                        {v.desc}
                      </p>
                      <p>
                        {v.tags.map((item: string, ind: number) => {
                          return (
                            <Tag
                              className="tagChild"
                              color={colors[ind]}
                              key={ind + "a"}
                            >
                              {item}
                            </Tag>
                          );
                        })}
                      </p>
                      <p>
                        <span>{v.price}</span>源/月
                      </p>
                    </div>
                  </div>
                );
              })}
          </div>
        </BeScroll>
      </div>
    </div>
  );
}
